#include <fstream>
#include <spdlog/spdlog.h>
#include "nlohmann/json.hpp"
#include "scan.h"

QList<std::shared_ptr<VideoInfo> > scan::scanVideoFiles(const QString &path) {
    QList<std::shared_ptr<VideoInfo> > videoInfoList;
    for (const auto &entry: std::filesystem::directory_iterator(path.toStdString())) {
        if (is_directory(entry.status())) {
            const auto &vidoInfo = parserVideoInfo(entry.path());
            if (vidoInfo != nullptr) {
                videoInfoList.append(vidoInfo);
            }
        }
    }
    return videoInfoList;
}

std::shared_ptr<VideoInfo> scan::parserVideoInfo(const std::filesystem::path &path) {
    const std::filesystem::path videoInfoPath = path / "videoInfo.json";
    if (is_regular_file(status(videoInfoPath))) {
        try {
            std::ifstream voidInfoFP(videoInfoPath);
            auto jsonData = nlohmann::json::parse(voidInfoFP);
            voidInfoFP.close();
            return std::make_shared<VideoInfo>(jsonData);
        } catch (const nlohmann::json::parse_error &e) {
            spdlog::error("Parse error: {}", e.what());
        } catch (const nlohmann::json::out_of_range &e) {
            spdlog::error("Out of range error: {}", e.what());
        } catch (const nlohmann::json::type_error & e) {
            spdlog::error("Type error: {}", e.what());
        }
    }
    return nullptr;
}
